﻿package com.xt.yncu.html;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.xt.base.util.DateUtils;
import com.xt.yncu.util.Config;
/**
 * <br>
 * <br>
 * 
 * <p>
 * <a href=".java.html"><i>查看源文件</i></a>
 * </p>
 * 
 * @author 邵勇
 * @create-date:2011-11-8
 */
public class EmailParseHtml {
	private static Logger log = Logger.getLogger(EmailParseHtml.class);
	private String title;
	private String date;
	private String author;
	private String content;
	private StringBuilder tableHtml;
	private StringBuilder attTableHtml;
	private boolean isKJava=false;
	/* 生成的HTML名称 */
	public String createHtmlName;

	private Config config;
	private Document document;
	private Element root;
	private Element element;

	/* 保存附件路径 */
	public List<String> fileList = new ArrayList<String>();
	/* 文件标识 */
	public List<String> fileInfoid = new ArrayList<String>();
	/* 邮件唯一ID */
	public String universalid;

	@SuppressWarnings("unchecked")
	public String xmlParse(String xml) {
		tableHtml = new StringBuilder();
		try {
			if (!isKJava) {
				tableHtml
				.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><title></title></head><body style=\"padding:0px; margin:0px; font-size:12px\">");
			}
			tableHtml
					.append("<table  border=\"0\" cellspacing=\"1\" cellpadding=\"6\"  width=\"100%\"  bgcolor=\"#FF0000\">");
			document = DocumentHelper.parseText(xml);
			root = document.getRootElement();
			title = getNodeString(root, "title");
			date = getNodeString(root, "date");
			author = getNodeString(root, "author");
			content = getNodeString(root, "content");
			this.setUniversalid(getNodeString(root, "universalid"));
			tableHtml.append("<tr  bgcolor=\"#ffffff\"><td width=\"100\">标    题:</td><td>").append(
					title).append("</td></tr>");
			tableHtml.append("<tr  bgcolor=\"#ffffff\"><td width=\"100\">时   间:</td><td>").append(
					timeToString(date)).append("</td></tr>");
			tableHtml.append("<tr  bgcolor=\"#ffffff\"><td width=\"100\">发件人:</td><td>").append(
					author).append("</td></tr>");
			tableHtml.append("<tr  bgcolor=\"#ffffff\"><td width=\"100\">邮件内容:</td><td>").append(
					content).append("</td></tr>");
			// 附件解析
			List<Object> listAttachment = root
					.selectNodes("//attachment/list/value");
			if (listAttachment != null && !listAttachment.isEmpty()) {
				tableHtml
						.append("<tr bgcolor=\"#ffffff\"><td colspan=\"2\">附件:</td></tr>");
				tableHtml.append(parseAttachment(listAttachment));
			}
			tableHtml.append("</table>");
			if (!isKJava) {
				tableHtml.append("</body></html>");
			}
		} catch (Exception e) {
			log.error("Email解析Xml出误(com/xt/yncu/html/EmailParseHtml.java)", e);
		}
		return tableHtml.toString();
	}

	/**
	 * 附件解析
	 */
	private String parseAttachment(List<Object> attList) {
		String fileName, fileInfoid;
		int attSize=0;
		List<Object> list = attList;
		attTableHtml = new StringBuilder();
		if (list != null && !list.isEmpty()) {
			for (int i = 0; i < list.size(); i++) {
				element = (Element) list.get(i);
				if (hasRootElement(element)) {
					fileName = getNodeString(element, "att_zh_name");
					fileInfoid = getNodeString(element, "att_infoid");
					attSize=StringUtils.isEmpty(getNodeString(element, "attsize"))?0:Integer.parseInt(getNodeString(element, "attsize"));
					if (StringUtils.isNotEmpty(fileName)) {
						attTableHtml
								.append("<tr bgcolor=\"#ffffff\"><td colspan=\"2\">");
						if (fileParse(fileName)) {
							attTableHtml.append("<font size=\"+1\">");
							attTableHtml.append(fileName);
							attTableHtml.append("</font>");
							if (isKJava) {
								attTableHtml.append("[请用电脑查看]");
							}else {
								if (attSize>getAttSize()) {
									attTableHtml.append("[文件过大，请用电脑查看!]");
								}else {
									attTableHtml
									.append(attachmentHtml(fileName, i + 10));
									this.setFileInfoid(fileInfoid);
								}
							}
						} else {
							if (isKJava) {
								attTableHtml.append(fileName).append("[请用电脑查看]");
							}else {
								attTableHtml.append(fileName).append("[不支持]");
							}
						}
						attTableHtml.append("</td></tr>");
					}
				}
			}
		}
		return attTableHtml.toString();
	}
	private String attachmentHtml(String fileName, int i) {
		StringBuilder sb = new StringBuilder();
		sb.append("<div name='attachNameDiv'>").append(fileName).append("</div>");
		return sb.toString();
	}
	/**
	 * 附件HTML
	 */
	/*private String attachmentHtml(String fileName, int i) {
		StringBuilder html = new StringBuilder();
		String fileExtension = other.getExtension(fileName);
		String newFileName = other.createSaveName() + (i * 10);
		if (fileParse(fileExtension)) {
			return "";
		}
		if (StringUtils.isEmpty(fileExtension)) {
			return "";
		}
		StringBuilder allFileName = new StringBuilder();
		allFileName.append(newFileName).append(".").append(fileExtension);
		html.append("&nbsp;&nbsp;");
		// html.append("<span id=\"").append(newFileName).append("\"></span>");
		html.append("<iframe src=\"");
		html.append(config.getNetworkAddress());
		html.append("/attachment/attachmentAction!fileIsExit.action");
		html.append("?fileName=").append(String.valueOf(allFileName));
		html.append("&htmlId=").append(newFileName);
		html
				.append("\" frameborder=\"0\" scrolling=\"no\" width=\"130\" height=\"35\">");
		html.append("</iframe>");
		this.setFileList(String.valueOf(allFileName));
		return String.valueOf(html);
	}*/

	/**
	 * 查找节点是否存在
	 * */
	@SuppressWarnings("unchecked")
	private boolean nodeIsExit(Element node, String nodeName) {
		List<Object> nodeList = node.selectNodes(nodeName);
		if (nodeList.size() > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 取得节点值
	 * */
	private String getNodeString(Element node, String nodeName) {
		if (nodeIsExit(node, nodeName)) {
			return node.element(nodeName).getTextTrim();
		}
		return null;
	}

	/** 判断是否有下层结点 */
	@SuppressWarnings( { "unchecked" })
	private boolean hasRootElement(Element root) {
		boolean flag = false;
		List<Object> list = root.elements();
		for (int i = 0; i < list.size(); i++) {
			String elementStr = ((Element) list.get(i)).getTextTrim();
			if (StringUtils.isNotEmpty(elementStr)) {
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * 文件是否能解析
	 * */
	private boolean fileParse(String fileName) {
		String ext = "|" + getExtension(fileName) + "|";
		if (config.getFileExtension().indexOf(ext) >= 0) {
			return true;
		}
		return false;
	}

	/**
	 * 获取文件扩展名
	 */
	private String getExtension(String fileName) {
		if ((fileName != null) && (fileName.length() > 0)) {
			int i = fileName.lastIndexOf('.');
			if ((i > -1) && (i < (fileName.length() - 1))) {
				return fileName.substring(i + 1).toLowerCase();
			}
		}
		return null;
	}

	/** 是否是XML文件 */
	private boolean isXMLString(String xmlString) {
		String xmlTop = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				.toLowerCase();
		xmlString = xmlString.toLowerCase();
		if (xmlString.indexOf(xmlTop) < 0) {
			return true;
		}
		return false;
	}

	/** 不是XML返回值 */
	private String errorXmlString(String xmlString) {
		StringBuilder xmlBuilder = new StringBuilder();
		xmlBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		xmlBuilder.append("<mobile>");
		xmlBuilder.append("<exception><![CDATA[WebService异常,异常信息为:").append(
				xmlString).append("]]></exception>");
		xmlBuilder.append("</mobile>");
		return String.valueOf(xmlBuilder);
	}

	/**
	 * 时间转换
	 * */
	public String timeToString(String date) {
		if (StringUtils.isEmpty(date)) {
			return null;
		}
		try {
			Date date2 = new Date(Long.parseLong(date));
			log.info("======================================");
			log.info(DateUtils.format(date2, "yyyy年MM月dd日"));
			log.info("======================================");
			return DateUtils.format(date2, "yyyy年MM月dd日");
		} catch (Exception e) {
			log.error("字符串转为时间出错com/xt/yncu/html/EmailParseHtml.java", e);
		}
		return null;
	}
	/** 判断返回信息是否异常 */
	@SuppressWarnings("unused")
	private boolean webServiceErr(String xmlString) {
		boolean bool = false;
		try {
			Document document = DocumentHelper.parseText(xmlString);
			Element root = document.getRootElement();
			try {
				String exception = root.element("exception").getTextTrim();
				bool = true;
			} catch (Exception e) {
				bool = false;
			}

		} catch (DocumentException e) {
			e.printStackTrace();
			bool = true;
		}
		return bool;
	}
	/**
	 *  为手机端生成Xml */
	/*public String mobileNewXml(String xml){
		StringBuilder savePath;
		StringBuilder imagePath;
		other=new OfficeOther();
		String htmlName = other.createSaveName();
		if (isXMLString(xml)) {
			return errorXmlString(xml);
		}else if (webServiceErr(xml)) {
			return xml;
		}			
		else if (isKJava) {
			String htmlString = xmlParse(xml);
			System.out.println(htmlString);
			savePath=new StringBuilder();
			imagePath=new StringBuilder();
			
			savePath = new StringBuilder();
			savePath.append(other.createFolder(config.getProcessFolder()))
					.append("\\");
			savePath.append(htmlName);
			imagePath.append(savePath.toString()).append(".png");
			savePath.append(".html");
			other.htmlToImage(htmlString, imagePath.toString());
			// 生成程批件Html
			other.writeFile(wapHtml(htmlName+".png"), savePath.toString());
			savePath = new StringBuilder();
			savePath.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			savePath.append("<mobile><content><![CDATA[");
			savePath.append(config.getNetworkAddress()).append("/").append(config.getProcessFolder()).append("/");
			savePath.append(htmlName);
			savePath.append(".html");
			savePath.append("]]></content></mobile>");
			return savePath.toString();
		}else {
			String htmlString = xmlParse(xml);
			savePath = new StringBuilder();
			savePath.append(other.createFolder(config.getProcessFolder()))
					.append("\\");
			savePath.append(htmlName);
			savePath.append(".html");
			setCreateHtmlName(htmlName);
			// 生成程批件Html
			other.writeFile(htmlString, savePath.toString());
			savePath = new StringBuilder();
			savePath.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			savePath.append("<mobile><content><![CDATA[");
			savePath.append(config.getNetworkAddress());
			savePath.append("/iframe.jsp?fileName=");
			savePath.append(htmlName);
			savePath.append("&folder=").append(config.getProcessFolder());
			savePath.append("]]></content></mobile>");
			return savePath.toString();
		}
	}*/
	/**
	 * WAP版HTML内容
	 * */
	private String wapHtml(String imageName){
		StringBuilder htmlBuilder=new StringBuilder();
		htmlBuilder.append("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.1//EN\" \"http://www.wapforum.org/DTD/wml_1.1.xml\">");
		htmlBuilder.append("<wml>");
		htmlBuilder.append("<card id=\"index\"><img src=\"").append(imageName).append("\"/>");
		htmlBuilder.append("</card></wml>");
		return htmlBuilder.toString();
	}
	public boolean isKJava() {
		return isKJava;
	}

	public void setKJava(boolean isKJava) {
		this.isKJava = isKJava;
	}

	public Config getConfig() {
		return config;
	}

	public void setConfig(Config config) {
		this.config = config;
	}

	public List<String> getFileList() {
		return fileList;
	}

	public void setFileList(String fileName) {
		this.fileList.add(fileName);
	}

	public List<String> getFileInfoid() {
		return fileInfoid;
	}

	public void setFileInfoid(String fileName) {
		this.fileInfoid.add(fileName);
	}

	public String getCreateHtmlName() {
		return createHtmlName;
	}

	public void setCreateHtmlName(String createHtmlName) {
		this.createHtmlName = createHtmlName;
	}
	public String getUniversalid() {
		return universalid;
	}

	public void setUniversalid(String universalid) {
		this.universalid = universalid;
	}
	/**
	 * 读取文件
	 * */
	private String openFile(String filePath) {
		StringBuilder fileContent = new StringBuilder();
		try {
			File f = new File(filePath);
			InputStreamReader fileReader = new InputStreamReader(
					new FileInputStream(f), "UTF-8");
			BufferedReader reader = new BufferedReader(fileReader);
			String line = "";
			while ((line = reader.readLine()) != null) {
				fileContent.append(line);
			}
			reader.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return String.valueOf(fileContent);
	}
	private int getAttSize(){
		return config.getAttSize()*1024*1024;
	}
	
	public static void main(String[] args) {
		EmailParseHtml x=new EmailParseHtml();
		String xml=x.openFile("E:\\Work\\YnCuService_D\\WebRoot\\xml\\email_show_2.xml");
		x.setKJava(true);
		//System.out.println(x.mobileNewXml(xml));
	}
}
